package cn.jorian.framework.service.impl;

import cn.jorian.framework.bean.LoginUser;
import cn.jorian.framework.entity.User;
import cn.jorian.framework.mapper.PermissMapper;
import cn.jorian.framework.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissMapper permissMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名错误");
        }

//        List<String> permiss = new ArrayList<>();
//        permiss.add("test");

        List<String> permiss = permissMapper.getPermiss(user.getId());

        return new LoginUser(user, permiss);
    }
}
